package net.danielpaz.pucc.poo.trabalho.model;

/**
 * Classe para manipular dados de objetos da classe Rota no banco de dados
 * @author Rodolfo
 * @date 14/06/2014
 *
 */


import java.sql.*;

public class RotaDAO {

	public Rota rota;
	public Conexao bd;
	private PreparedStatement statement;
	private ResultSet resultSet;
	private String men, sql;
	public static final byte INCLUSAO = 1;
	public static final byte ALTERACAO = 2;
	public static final byte EXCLUSAO = 3;

	public RotaDAO() {
		bd = new Conexao();
		rota = new Rota();
		bd.getConnection();
	}

	public boolean localizar(int id) {

		sql = "SELECT * FROM ROTA WHERE ID = ?";

		try {

			System.out.println(sql);

			statement = bd.connection.prepareStatement(sql);
			statement.setInt(1, id);
			resultSet = statement.executeQuery();

			while (resultSet.next()) {
				rota.setId(Integer.parseInt(resultSet.getString(1)));
				rota.setId_motorista(Integer.parseInt(resultSet.getString(2)));
				rota.setId_veiculo(Integer.parseInt(resultSet.getString(3)));
				rota.setId_destino(Integer.parseInt(resultSet.getString(4)));
				rota.setId_origem(Integer.parseInt(resultSet.getString(5)));
				rota.setDuracao(Integer.parseInt(resultSet.getString(6)));
			}
			
			return true;
			
		} catch (Exception erro) {
			
			erro.printStackTrace();
			System.out.println(erro.getMessage());
			return false;
		}
	}

	public String atualizar(int operacao) {

		men = "Operacao realizada com sucesso!";

		try {
			if (operacao == INCLUSAO) { 
				sql = "INSERT INTO ROTA VALUES (?)";
				statement = bd.connection.prepareStatement(sql);
				
				/*
				 * Caso o campo ID da tabela seja auto-increment, apagar esta linha
				 * statement.setString(1, "" + rota.getId());
				 */
				
				statement.setString(1, "" + rota.getId());
                statement.setString(2, "" + rota.getId_motorista());
                statement.setString(3, "" + rota.getId_veiculo());
                statement.setString(4, "" + rota.getId_destino());
                statement.setString(5, "" + rota.getId_origem());
                statement.setString(6, "" + rota.getDuracao());
				
			} else if (operacao == ALTERACAO) {
				
				sql = "UPDATE ROTA SET DURACAO = ? WHERE ID = ?";
				statement = bd.connection.prepareStatement(sql);
				statement.setString(1, "" + rota.getDuracao());
				statement.setString(2, "" + rota.getId());

			} else if (operacao == EXCLUSAO) {
				
				sql = "DELETE FROM ROTA WHERE ID = ?";
				statement = bd.connection.prepareStatement(sql);
				statement.setString(1, "" + rota.getId());
				
			}
			
			if (statement.executeUpdate() == 0)
				men = "Falha na operacao!";
			
		} catch (SQLException erro) {
			men = "Falha na operacao " + erro.toString();
		}
		return men;
	}

}
